package service

import (
	cmodel "ksd-social-api/modules/special/model"
	"strconv"
)

/**
 * 用户购买专栏
 * @author feige
 * @date 2023-11-23
 * @version 1.0
 * @desc
 */
type UserSpecialBindService struct {
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  保存用户购买专栏信息
 */
func (service *UserSpecialBindService) SaveUserSpecialBind(
	OutTradeNo string, TransactionId string, orderJson string, payMethod int, payMethodName string, price string,
	userId uint64, opid uint64, specialId uint64, systemId uint64, systemName string) bool {
	// 1： 判断用户是否购买此课程，如果购买过了就就不要去保存订单
	isBuyFlag := userBuySpecialBindMapper.CountUserBuySpecialBindNo(userId, specialId, opid, systemId)
	if isBuyFlag == 0 {
		userBuySpecialBind := cmodel.SpecialBindUserBuy{}
		// 根据课程id查询课程信息
		specialBind, _ := specialBindMapper.GetSpecialBinds(opid, systemId)
		special, _ := specialMapper.GetById(opid, systemId)
		userVo := userMapper.GetUserByID(userId, systemId)

		userBuySpecialBind.SystemId = systemId
		userBuySpecialBind.SystemName = systemName
		userBuySpecialBind.SpecialId = specialId
		// 处理返回结果
		userBuySpecialBind.Opid = opid
		userBuySpecialBind.Title = special.Title + "-" + specialBind.Title
		userBuySpecialBind.Cover = special.Img

		userBuySpecialBind.UserId = userId
		userBuySpecialBind.Username = userVo.Username
		userBuySpecialBind.Avatar = userVo.Avatar
		userBuySpecialBind.Uuid = userVo.Uuid
		userBuySpecialBind.Phone = userVo.Telephone
		userBuySpecialBind.Address = userVo.Address
		userBuySpecialBind.Nickname = userVo.Nickname

		userBuySpecialBind.Code = ""
		userBuySpecialBind.PayMethod = payMethod
		userBuySpecialBind.PayMethodName = payMethodName
		userBuySpecialBind.Tradeno = OutTradeNo
		userBuySpecialBind.Orderno = TransactionId
		userBuySpecialBind.OrderJson = orderJson
		userBuySpecialBind.Price = price
		userBuySpecialBindMapper.SaveUserBuySpecialBind(userBuySpecialBind)

		// 开始查询所有的订单的金额是否大于专题订购的总价，自动开通所有权限
		sumBindPrice := userBuySpecialBindMapper.SumUserBuySpecialBindPrice(userId, specialId, systemId)
		if len(sumBindPrice) > 0 {
			Price, _ := strconv.Atoi(sumBindPrice)
			SPrice, _ := strconv.Atoi(special.Price)
			if Price >= SPrice {
				userSpecialService.SaveUserSpecial(OutTradeNo, TransactionId, "", 1, "微信", special.Price,
					userId, specialId, systemId, systemName)
			}
		}

		return true
	}
	return false
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  判断用户是否购买此专栏
 */
func (service *UserSpecialBindService) CountUserBuySpecialBind(userId uint64, specialId uint64, bindId uint64, systemId uint64) bool {
	// 1： 判断用户是否购买此专栏，如果购买过了就就不要去保存订单
	isBuyFlag := userBuySpecialBindMapper.CountUserBuySpecialBindNo(userId, specialId, bindId, systemId)
	return isBuyFlag == 0
}
